﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Ongoal.Quotation;
using Ongoal.Quotation.Service;
using Ongoal.Quotation.Service.Model;
using System.Security.Claims;
using System.Text;

namespace Ongoal.Quotation.WebAPI.Controllers
{
    /// <summary>
    /// 登录相关
    /// </summary>
    [Route("Login")]
    public class LoginController : WebAPIBase
    {
        private ILoginService _service;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="service"></param>
        public LoginController(ILoginService service)
        {
            _service = service;
            //_service = ServiceProviderContext.ServiceProvider.GetService(typeof(ILoginService)) as ILoginService;
            //if (_service != null)
            //{
            //    Logger.LogInformation("呵呵");
            //}
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="codeStr">密码</param>
        /// <param name="encryptKey">时间期限口令</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        [HttpGet]
        [AllowAnonymous]
        public LoginResult Login(string userName, string codeStr,string encryptKey)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(codeStr))
            {
                throw new ArgumentNullException("请输入用户名密码");
            }
            if (string.IsNullOrEmpty(encryptKey))
            {
                throw new ArgumentNullException("没有找到对应的时间戳信息");
            }
            //解密
            userName = Des.Decrypt(userName, Des.DefaultKEY);
            codeStr = Des.Decrypt(codeStr, Des.DefaultKEY);
            encryptKey = Des.Decrypt(encryptKey, Des.DefaultKEY);

            //暂时取消对登录时间的限制
            //System.DateTime startTime =  TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            //DateTime LoginTime = startTime.AddMilliseconds(Convert.ToDouble(encryptKey));
            //if (LoginTime.AddMinutes(1) < DateTime.Now)
            //{
            //    throw new Exception("登录信息已经过期");
            //}

            //解码
            userName = System.Net.WebUtility.UrlDecode(userName).Trim();
            codeStr = System.Net.WebUtility.UrlDecode(codeStr).Trim();
            var ipaddress = string.Empty;
            try
            {
                if (this.Request.Headers.Keys.Contains("X-Real-IP"))
                {
                    ipaddress = this.Request.Headers["X-Real-IP"].ToString();
                }
                else if (this.Request.Headers.Keys.Contains("X-Forwarded-For"))
                {
                    ipaddress = this.Request.Headers["X-Forwarded-For"].ToString();
                }
                else
                {
                    ipaddress = HttpContext.Connection.RemoteIpAddress.ToString();
                }

            } catch
            { 
            }
            
            LoginResult result = new LoginResult();
            result.SessionID = Guid.NewGuid().ToString("N");
            var info = _service.LoginCheck(userName, codeStr, ipaddress);
            if (info != null)
            {
                var _jwt = ServiceProviderContext.ServiceProvider.GetService(typeof(IAuthentication)) as IAuthentication;
                List<Claim> clims = new List<Claim>();
                //clims.Add(new Claim("tokenid", info.TokenID!));
                clims.Add(new Claim("loginuser", Des.Encrypt(JsonConvert.SerializeObject(info))));
                clims.Add(new Claim("logintimes", JsonConvert.SerializeObject(DateTime.Now)));
                clims.Add(new Claim("sessionid", result.SessionID));
                result.User = info;
                result.Token = _jwt!.GetToken(clims);
                result.RefreshToken = _jwt!.GetRefreshToken(clims);
                return result;
            }
            else
            {
                throw new Exception("找不到对应的用户");
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="codeStr">密码</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="Exception"></exception>
        [HttpGet]
        [Route("Login1")]
        [AllowAnonymous]
        public LoginResult Login1(string userName, string codeStr)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(codeStr))
            {
                throw new ArgumentNullException("请输入用户名密码");
            }
            var ipaddress = string.Empty;
            try
            {
                if (this.Request.Headers.Keys.Contains("X-Real-IP"))
                {
                    ipaddress = this.Request.Headers["X-Real-IP"].ToString();
                }
                else if (this.Request.Headers.Keys.Contains("X-Forwarded-For"))
                {
                    ipaddress = this.Request.Headers["X-Forwarded-For"].ToString();
                }
                else
                {
                    ipaddress = HttpContext.Connection.RemoteIpAddress.ToString();
                }

            }
            catch
            {
            }

            LoginResult result = new LoginResult();
            result.SessionID = Guid.NewGuid().ToString("N");
            var info = _service.LoginCheck(userName, codeStr, ipaddress);
            if (info != null)
            {
                var _jwt = ServiceProviderContext.ServiceProvider.GetService(typeof(IAuthentication)) as IAuthentication;
                List<Claim> clims = new List<Claim>();
                //clims.Add(new Claim("tokenid", info.TokenID!));
                clims.Add(new Claim("loginuser", Des.Encrypt(JsonConvert.SerializeObject(info))));
                clims.Add(new Claim("logintimes", JsonConvert.SerializeObject(DateTime.Now)));
                clims.Add(new Claim("sessionid", result.SessionID));
                result.User = info;
                result.Token = _jwt!.GetToken(clims);
                result.RefreshToken = _jwt!.GetRefreshToken(clims);
                return result;
            }
            else
            {
                throw new Exception("找不到对应的用户");
            }
        }

    }
}
